<template>
  <div style="margin-top: 50px"></div>
  <el-form
    ref="ruleFormRef"
    :model="ruleForm"
    style="max-width: 500px"
    label-width="auto"
    class="demo-ruleForm"
  >
    <el-form-item
      label="公司名称"
      prop="companyname"
      :rule="[{ required: true, message: '请输入公司名称', trigger: 'blur' }]"
    >
      <el-input style="width: 300px" v-model="ruleForm.companyName" />
    </el-form-item>
    <el-form-item
      label="公司类型"
      prop="companyStyle"
      :rule="[{ required: true, message: '请选择公司类型', trigger: 'blur' }]"
    >
      <el-select style="width: 300px" v-model="ruleForm.companyStyle" placeholder="公司类型">
        <el-option
          v-for="item in companytypes"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="数据文件" prop="datafile">
      <el-upload
        style="width: 300px"
        class="upload-demo"
        drag
        :limit="1"
        :before-upload="onSubmit"
        :http-request="httpRequest"
      >
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">拖拽 或 <em>点击</em> 上传</div>
        <template #tip>
          <div class="el-upload__tip">请上传docx文件,不超过500kb</div>
        </template>
      </el-upload>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
      <el-button @click="resetForm(ruleFormRef)">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, type FormInstance } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import axios from 'axios'
import { setCarbonEmission } from '@/utils/useWeb3'
import { CarbonEmissionControllerService, CompanyUserControllerService } from '../../../generated'
import { useUserStore } from '@/stores/user'

const companytypes = [
  { label: '发电企业', value: '发电企业' },
  { label: '电网企业', value: '电网企业' },
  { label: '电解铝企业', value: '电解铝企业' },
  { label: '民航企业', value: '民航企业' }
]
const wallet = reactive(JSON.parse(localStorage.getItem('wallet') as string) || {})
const ruleFormRef = ref<FormInstance>()
const ruleForm = ref({
  companyName: '',
  companyStyle: '',
  year: '2024',
  file: ''
})
const user = useUserStore()
const httpRequest = (file: any) => {
  ruleForm.value.file = file.file
  console.log(file.file)
}
const loadData = async () => {
  const res = await CompanyUserControllerService.getByUserIdUsingPost(user.id)
  ruleForm.value.companyName = res.data.companyName
  ruleForm.value.companyStyle = res.data.type


}
const onSubmit = (file: any) => {
  console.log(file.size)
}
/**
 * 碳核算
 * @param formEl
 */
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      const formData = new FormData()
      formData.append('companyName', ruleForm.value.companyName)
      formData.append('companyStyle', ruleForm.value.companyStyle)
      formData.append('file', ruleForm.value.file)
      formData.append('year', ruleForm.value.year)
      console.log(formData)
      //1.碳核算-》获取碳排放数据
      axios.post('/bbb/carbonEmission', formData).then(async (res) => {
        if (res.data.code === 0) {
          const res2 = await CarbonEmissionControllerService.seachUsingGet(
            ruleForm.value.companyName,
            ruleForm.value.year
          )
          // console.log(res2)
          //2.碳排放上传区块链
          const res3 = await setCarbonEmission(
            wallet.address,
            ruleForm.value.year,
            Number.parseInt(res2.data.emission)
          )
          if (res3.status != 0) {
            ElMessage({
              message: '碳核算失败-区块链异常',
              type: 'error'
            })
          } else {
            //todo 修改数据库
            const res4 = await CompanyUserControllerService.getCompanyUsingGet()
            const res5 = await CarbonEmissionControllerService.updateUsingPost({
              companyId: res4.data?.id,
              year: '2024',
              blockchainId: res3.blockchainId
            })
            ElMessage({
              message: '碳核算成功',
              type: 'success'
            })
          }
        }
      })
    } else {
      ElMessage({
        message: '碳核算失败-数据库异常',
        type: 'error'
      })
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

onMounted(() => {
  loadData()

})
</script>
<style scoped>
.demo-ruleForm {
  margin: 50px auto;
}
</style>
